package com.fwj.authorization.security;

import com.fwj.authorization.security.Exception.MyAccessDeniedHandler;
import com.fwj.authorization.security.Exception.MyAuthenticationEntryPoint;
import com.fwj.authorization.security.verifyCode.CustomAuthenticationProvider;
import com.fwj.authorization.security.verifyCode.VerifyServlet;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author fwj
 * @date 2025/03/18
 */
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Resource
    private AuthenticationSuccessHandler authenticationSuccessHandler;

    @Resource
    private AuthenticationFailureHandler authenticationFailureHandler;

    @Resource
    private MyAuthenticationEntryPoint myAuthenticationEntryPoint;

    @Resource
    private MyAccessDeniedHandler myAccessDeniedHandler;

    @Resource
    private SysUserDetailsService sysUserDetailsService;

    @Resource
    private AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> authenticationDetailsSource;

    /* 自己编写的认证逻辑替换系统自带认证 */
    @Resource
    private CustomAuthenticationProvider customAuthenticationProvider;

    @Value("${security.oauth2.ignore-urls}")
    private List<String> ignoreUrl;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /* 注册自己编写的认证逻辑 */
        auth.authenticationProvider(customAuthenticationProvider);
        auth.userDetailsService(sysUserDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        /* 设置拦截忽略文件夹，可以对静态资源放行 */
        web.ignoring().antMatchers("/static/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .formLogin()
                .loginPage("/login.html")
                .loginProcessingUrl("/auth/login")
                .successHandler(authenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler)
                /* 验证码 */
                .authenticationDetailsSource(authenticationDetailsSource)
                .and()
                .logout()
                .logoutUrl("/auth/logout")
                .logoutSuccessUrl("/login.html")
                .and()
                .authorizeRequests()
                /* 认证+验权处理 */
                .antMatchers(String.join(",", ignoreUrl))
                .permitAll()
                .anyRequest()
                .access("@custom.hasPermission(request, authentication)")
                //.and()
                /* 禁用session 不可放开 */
                //.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .csrf().disable();
        /* 注册自定义异常 */
        http.exceptionHandling().authenticationEntryPoint(myAuthenticationEntryPoint).accessDeniedHandler(myAccessDeniedHandler);
    }

    /**
     * 密码加密
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 注入验证码servlet
     */
    @Bean
    public ServletRegistrationBean indexServletRegistration() {
        ServletRegistrationBean registration = new ServletRegistrationBean(new VerifyServlet());
        registration.addUrlMappings("/getVerifyCode");
        return registration;
    }
}
